const path = require("path");
const XLSX = require("xlsx");

function getDatabase(fileName = "dataset", suffix = ".xlsx") {
    return new Promise((resolve) => {
        workbook = XLSX.readFile(
            path.join(__dirname, "dataset", fileName + suffix)
        );
        resolve(workbook);
    }).catch((err) => {
        console.error(err);
    });
}

function getJsonBySheet(sheet) {
    return XLSX.utils.sheet_to_json(sheet);
}

function writeDataBase(sheetName, data) {
    return getDatabase().then((workbook) => {
        const workSheet = XLSX.utils.json_to_sheet(data);
        workbook.Sheets[sheetName] = workSheet;
        XLSX.writeFile(
            workbook,
            path.join(__dirname, "dataset", "dataset.xlsx")
        );
    });
}

module.exports = {
    getDatabase,
    getJsonBySheet,
    writeDataBase,
};
